import { defineStore } from "pinia";
import { addCartAPI, changeCheckedAllAPI, deleteCartAPI, fetchCartListAPI, updateCartGoodAPI } from "@/api/cartAPI";
import type { AddCartDTO, CartItemVO } from "@/types/cartType";
import { computed, ref } from "vue";

const useCartStore = defineStore("cartStore", () => {

   const cartList = ref<CartItemVO[]>([]);

   // 发送请求加入购物车的回调函数
   const addCart = async (data: AddCartDTO) => {
      try {
         await addCartAPI(data);
      } catch (error: any) {
         await error;
      }
   };
   // 发送请求获取购物车列表
   const fetchCartList = async () => {
      try {
         const { result }: { result: CartItemVO[] } = await fetchCartListAPI();
         cartList.value = result;
      } catch (error: any) {
         await error;
      }
   };
   // 发送请求删除购物车商品
   const deleteCart = async (skuIds: string[]) => {
      try {
         await deleteCartAPI(skuIds);
      } catch (error: any) {
         await error;
      }
   };
   // 发送修改购物车商品
   const updateCartGood = async (skuId: string, data: { selected?: boolean, count?: number }) => {
      try {
         await updateCartGoodAPI(skuId, data);
      } catch (error: any) {
         await error;
      }
   };
   // 发送请求全选/取消全选的
   const changeCheckedAll = async (selected: boolean) => {
      try {
         await changeCheckedAllAPI(selected);
      } catch (error: any) {
         await error;
      }
   };
   const isSelectedAll = computed(() => cartList.value.every(item => item.selected));
   const selectedCartList = computed(() => cartList.value.filter(item => item.selected));
   const totalPrice = computed(() => selectedCartList.value.reduce((sum, item) => sum + item.count * Number(item.price), 0));
   const totalGood=computed(()=>selectedCartList.value.reduce((sum,item)=>sum+item.count,0))
   return {
      cartList,
      isSelectedAll,
      totalPrice,
      totalGood,
      addCart,
      fetchCartList,
      deleteCart,
      updateCartGood,
      changeCheckedAll,

   };
});


export default useCartStore;